package com.foxitcloud.webpdf.common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class Signature {
	
	private HashMap<Integer, ArrayList<SignatureData>>	mapSignature;
	
	public Signature(){
		mapSignature = new HashMap<Integer, ArrayList<SignatureData>>();
	}
	
	/*
	 * 对json反序列化后的数据进行格式化，因为反序列化后的SignatureData对象需要转成对应的文本或图片对象
	 */
	public Signature(String jsonString){
		Gson gson = new Gson();	
		JsonParser jsonParser = new JsonParser();
		mapSignature = new HashMap<Integer, ArrayList<SignatureData>>();		
		try{
			JsonElement jsonElement = jsonParser.parse(jsonString);
			JsonObject jsonObj = jsonElement.getAsJsonObject().getAsJsonObject("mapSignature");
			Map<Integer, Object> jsonMapObj = gson.fromJson(jsonObj, new TypeToken<Map<Integer, ArrayList<Object>>>(){}.getType());
	         for(Integer key: jsonMapObj.keySet()){
	        	 ArrayList<Object> jsonArrayObj = (ArrayList<Object>)jsonMapObj.get(key);
	        	 int size = jsonArrayObj.size();
	        	 for(int i=0;i<size;i++){
	        		 String jsonObjString = gson.toJson(jsonArrayObj.get(i));
	        		 jsonElement = jsonParser.parse(jsonObjString);
	        		 int type = jsonElement.getAsJsonObject().get("type").getAsInt();
	        		 switch (type) {
						case 0:
						{
							TextSignatureData signatureData = gson.fromJson(jsonObjString, TextSignatureData.class);
							addSignatureData(key,signatureData);
						}
							break;
						case 1:
						{
							ImgSignatureData signatureData	= gson.fromJson(jsonObjString, ImgSignatureData.class);
							addSignatureData(key,signatureData);
						}
						break;
					default:
						break;
					}
	        	 }
	         }
		}catch(Exception e){
			//add err log...
		}	   
		
	}
	
	
	public void addSignatureData(int index,SignatureData signData){
		
		ArrayList<SignatureData> signList = mapSignature.get(index);
		if(null == signList){
			signList = new ArrayList<SignatureData>();
			mapSignature.put(index, signList);
		}		
		signList.add(signData);			
	}
	
	public Queue<Integer> getSignaturePageIndexs(){
		Queue<Integer> signaturePageIndex = new LinkedList<Integer>();
		for(Map.Entry<Integer, ArrayList<SignatureData>> entry:mapSignature.entrySet()){
			signaturePageIndex.offer(entry.getKey());
		}
		return signaturePageIndex;
	}
}
